package com.zbs.framework.security.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbs.framework.security.entity.LoginUserInfo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: Zbs
 * @createTime: 2021/3/31 15:39
 */
@Component
public class ThreadLocalClient {
    public static LoginUserInfo getUser(){
        final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (String.valueOf(principal).equals("anonymousUser")){
            return new LoginUserInfo();
        }else {
            return (LoginUserInfo)principal;
        }
    }

    public static Object getOtherInfo(String key) {
        Map<String, Object> otherInfo = getUser().getOtherInfo();
        if (otherInfo.containsKey(key)) {
            return otherInfo.get(key);
        }
        return null;
    }

    public static <T> T getOtherInfo(String key,Class<T> clazz) {
        Map<String, Object> otherInfo = getUser().getOtherInfo();
        if (otherInfo.containsKey(key)) {
            return new ObjectMapper().convertValue(otherInfo.get(key),clazz);
        }
        return null;
    }

    public static <T> List<T> getOtherInfoList(String key, Class<T> clazz) {
        Map<String, Object> otherInfo = getUser().getOtherInfo();
        List<T> list = new ArrayList<>();
        if (otherInfo.containsKey(key)) {
            Object obj = otherInfo.get(key);
            if (obj instanceof List<?>) {
                for (Object o : (List<?>) obj) {
                    list.add(clazz.cast(o));
                }
                return list;
            }
        }
        return list;
    }


    public static String getUserName(){
        return getUser().getUsername();
    }

    public static Map<String,Object> getOtherInfo(){
        return getUser().getOtherInfo();
    }

    public static boolean getUserIsEnable(){
        return getUser().isEnabled();
    }

    public static Long getUserId(){
        return getUser().getId();
    }


    public static Character getUserType(){
        return getUser().getUserType();
    }

}
